define(function(require) {
	
	var $ = require("jquery");
	var Confirmbox = require("confirmbox");
	var Validator = require("validator");
	var utils = require("utils");
	var ctx = utils.constants.ctx;
	var ui = require("ui");
	
	var backManagerService = require("bean/backManagerService");
	//添加
	$.post(ctx + '/back/base/userIdentityEditUI',function(data){
		var confirmBox = new Confirmbox({
	        trigger: '#addUserIdentity',
	        title: '用户身份添加',
	        message: data,
	        onConfirm: function() {
	        	userIdentity_submit("add");
	        }
	    });
		confirmBox.after("show",function(){
			
			Validator.addRule('int_num', /^[1-9]\d*$/, '请输入合法的{{display}}');
			
			var validator = new Validator({
	            element: $("#userIdentity_form")
	        }).addItem({
	            element: '[name=userIdentityName]',
	            required: true
	        }).addItem({
	            element: '[name=userIdentityInitScore]',
	            required: true,
	            rule: 'int_num'
	        }).addItem({
	            element: '[name=identifier]',
	            required: true
	        });			
			
		});
		confirmBox.after("hide",function(){
			$("#userIdentityName").val("");
			$("#identifier").val("");
			$("#userIdentityInitScore").val("");
			$("#userIdentityDescn").val("");
		});
	});
	
	
	//修改
	var updateCb ;
	$(".jw_btn_Modify").bind("click",function(){
		
		var id = $(this).attr("data").replace("userIdentity_", "");
		
		$.post(ctx + '/back/base/userIdentityEditUI', {"userIdentityId":id},function(data){
			if(updateCb == null) {
				updateCb = new Confirmbox({
			        title: '用户身份修改',
			        effect: "fade",
			        message: data,
			        onConfirm: function() {
			        	userIdentity_submit("update");
			        }
			    });
			} else {
				updateCb.before("show",function(){
					this.set("message",data);
				});
			}
			updateCb.after("show",function(){
				Validator.addRule('int_num', /^[1-9]\d*$/, '请输入合法的{{display}}');
				
				var validator = new Validator({
		            element: $("#userIdentity_form")
		        }).addItem({
		            element: '[name=userIdentityName]',
		            required: true
		        }).addItem({
		            element: '[name=userIdentityInitScore]',
		            required: true,
		            rule: 'int_num'
		        }).addItem({
		            element: '[name=identifier]',
		            required: true
		        });
			});
			updateCb.show();
		});
	})
	
	
	var userIdentity_submit = function (type){
		var name = $("#userIdentityName").val();
		var identifier = $("#identifier").val();
		var initScore = $("#userIdentityInitScore").val();
		var descn = $("#userIdentityDescn").val();
		var id  = $("#userIdentityId").val();
		if(name == ""){
			$("#userIdentityName").trigger("focus");
			$("#userIdentityName").trigger("blur");
			return false;
		}
		if(identifier == ""){
			$("#identifier").trigger("focus");
			$("#identifier").trigger("blur");
			return false;
		}
		
		var userIdentity = {
	 			id : id,
    			name : name,
    			identifier : identifier,
    			initScore : initScore,
    			descn : descn
    		};
	 	
	 	try {
	 		ui.mask().show("请稍候...");
	 		if (type == "add"){
	 			backManagerService.userIdentityAdd(userIdentity)
	 			ui.mask().hide();
    	 		alert('添加成功');
	 		} else {
    	 		backManagerService.userIdentityUpdate(userIdentity);
    	 		ui.mask().hide();
		 		alert('修改成功');
	 		}
	 		location.href = ctx + "/back/base/userIdentityList";
	 	} catch (e){
	 		ui.mask().hide();
			alert(e.message);
	 	}
	}
	
	//删除
	$("#deleteUserList").bind("click",function(){
		if ($('input[name=items]:checkbox:checked').length <= 0) {
			alert("请选择用户身份");
			return;
		}
		if(!window.confirm("确定要删除用户身份信息？")){
			return;
		}
		var array = [];
		$('input[name=items]:checkbox:checked').each(function() {
		    	
			var id = $(this).attr("id").replace("userIdentity_", "");
			array.push(id);   
		});
		
		if (array.length != 0) {
			try{
				ui.mask().show("请稍候...");
				backManagerService.userIdentityDelete(array);
				ui.mask().hide();
				alert("删除成功");
				window.location.reload();
			} catch (e) {
				ui.mask().hide();
				alert("删除失败:"+e.message);
			}
		} 
	});
	
	
	//角色的分配权限
	var updateRolesCb;
	$(".jw_btn_role").bind("click",function(){
		
		var userIdentityId = $(this).attr("userIdentity_id").replace("userIdentity_", "");
		var roleIds = $(this).attr("roleIds").replace("userIdentity_", "");
		var data = '<div id="userIdentity_role_info" style="min-height: 100px;">';
		roleIds = eval('(' + roleIds + ')');
		var roles;
		try{
			roles = backManagerService.loadAllroles();
		} catch (e) {
			alert("加载数据失败:" + e.message);
			return;
		}
		
		for(var i=0;i<roles.length;i++) {
			
			var v = 20;
			if(roles[i].name != null && roles[i].name.length > 6) {
				v = 0;
			}
			var checked = '';
			if(roleIds.indexOf(roles[i].id) > -1) {
				checked = 'checked="checked"';
			}
			data += '<span style="overflow: hidden;margin-bottom:' + v + 'px;width: 100px;display: block;float: left;">' 
					+ '<input type="checkbox" ' + checked + ' name="userIdentity_roles" id="userIdentity_role_'
					+ roles[i].id + '">' + roles[i].name + '</span>';

		}
		data += '</div>'

		if(updateRolesCb == null) {
			updateRolesCb = new Confirmbox({
				
				trigger: '#userIdentity_role_confirmbox',
				title: "分配角色",
				message: data,
				width : 450,
				onConfirm: function() {
		
					var ch = $('#userIdentity_role_info input[name="userIdentity_roles"]');
					var newRoleIds = []; //新角色ids
					
					for(var i=0; i<ch.length;i++) {

						if("checked" == ch.eq(i).attr("checked")) {
							var id = parseInt(ch.eq(i).attr("id").replace("userIdentity_role_", ""));
							newRoleIds.push(id);
						}
					}
					
					try{

						backManagerService.userIdentityAllotRole(userIdentityId, newRoleIds);
						alert("分配角色成功！");
						this.hide();
						window.location.reload();
					} catch (e) {
						alert("分配角色失败:" + e.message);
						return;
					}
				}
			});
		} else {					
			updateRolesCb.before('show',function() {

		       this.set('message', "");
		       this.set('message', data);		       
		   });
		}
		updateRolesCb.show();
		
		//添加角色选择事件
		$('#userIdentity_role_info input[name="userIdentity_roles"]').bind("click", function(){

			if(typeof $(this).attr("checked") == "undefined") {
				$(this).attr("checked", "checked");
			} else {
				$(this).removeAttr("checked");
			}
		});
	});	
	
	//设置默认身份
	$(".jw_btn_default").bind("click",function(){
		
		var id = $(this).attr("data").replace("userIdentity_", "");
		
		try{
			backManagerService.setDefaultUserIdentity(id);
			alert("设置成功！");
			location.href = ctx + "/back/base/userIdentityList";
		} catch (e) {
			alert("设置失败:"+e.message);
		}
	});
	
	$("#searchBtn").bind("click",function(){
		var searchContent = $("#searchInfo").val();
		if(searchContent == null){
			alert("请输入搜索内容")
			return false ;
		}
		location.href = ctx+"/back/base/userIdentityList?name="+searchContent;
		
	});
});